import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { LoginService } from '../shared/services/login.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  validateForm: FormGroup;

  loginParams: any;

  user: any;

  constructor(
    private loginService: LoginService,
    private _message: NzMessageService,
    private fb: FormBuilder,
    private router: Router
  ) {
  }

  ngOnInit() {
    this.reset();
    this.validateForm = this.fb.group({
      userName: [ null, [ Validators.required ] ],
      password: [ null, [ Validators.required ] ],
      captcha: [ null, [ Validators.required ] ],
      remember: [ true ],
    });
    // 市场部帐号 15900525864
    // 运营部 13641793826
    // 产品部 15221271137
    // this.loginParams['username'] = '15221271137';
    // this.loginParams['password'] = 'Cote2016';
    // this.loginParams['captcha'] = 'CHDE';
    // 获取当前登录用户
    this.user = this.loginService.getUser();
    if (this.user) {
      this.router.navigate(['dashboard']);
    }

  }

  reset() {
    this.loginParams = {
      changeImg: true,
      username: '',
      password: '',
      captcha: '',
    };
  }

  changeImg() {
    const that = this;
    this.loginParams.changeImg = false;
    setTimeout(() => {
      that.loginParams.changeImg = true;
    }, 10);
  }

  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
  }

  login() {
    // console.log(this.validateForm);
    this.loginParams['username'] = this.validateForm.controls['userName']['value'];
    this.loginParams['password'] = this.validateForm.controls['password']['value'];
    this.loginParams['captcha'] = this.validateForm.controls['captcha']['value'];

    this._submitForm();
    //  || !this.loginParams['captcha']
    if (!this.loginParams['username'] || !this.loginParams['password']) {
      // this._message.success('请填写表单', {nzDuration: 2000});
      return false;
    }
    // console.log(this.loginParams);
    this.loginService.login(this.loginParams).subscribe(res => {
      // console.log(res);
      if (res['code'] === '0') {
        // 权限可以路由控制
        this.loginService.setUser(res['data']);
        this._message.success('登录成功', {nzDuration: 2000});
        this.router.navigate(['dashboard']);
      } else {
        this._message.error('登录错误,' + res['msg'], {nzDuration: 3000});
      }
    });
  }

}
